package com.itheima.controller;

import com.itheima.domain.Employee;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import java.util.List;

@Controller
public class EmployeeController {


    @RequestMapping("add")
    public ModelAndView add(@Validated Employee employee, Errors errors){
        ModelAndView modelAndView = new ModelAndView();
       if(errors.hasErrors()){
           List<FieldError> fieldErrors = errors.getFieldErrors();
           for (FieldError fieldError : fieldErrors) {
               modelAndView.addObject(fieldError.getField(),fieldError.getDefaultMessage());
               modelAndView.setViewName("index.jsp");
           }
           return modelAndView;
       }
       modelAndView.setViewName("success.jsp");
       return modelAndView;
    }

}
